package com.lanyuan.a.controller;


import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lanyuan.a.atest.UserFormMap;
import com.lanyuan.a.atest.UserGroupsFormMap;
import com.lanyuan.a.bean.User;
import com.lanyuan.a.service.ArticleService;
import com.lanyuan.a.service.ButtonService;
import com.lanyuan.a.service.UserService;
import com.lanyuan.annotation.SystemLog;
import com.lanyuan.controller.index.BaseController;
import com.lanyuan.exception.SystemException;
import com.lanyuan.plugin.PageView;
import com.lanyuan.util.Common;

@Controller
@RequestMapping("/user/")
public class UserController extends BaseController {
	@Autowired
	UserService userService;
	@Autowired
	ButtonService buttonService;
	@Resource
	ArticleService articleService;
	@RequestMapping("list")
	public String listUI(Model model) throws Exception {
		model.addAttribute("res", userService.findAllList());
		model.addAttribute("buttons", buttonService.getButtons("#user"));
		return Common.BACKGROUND_PATH + "/system/user/list";
	}

	@ResponseBody
	@RequestMapping("findByPage")
	public PageView findByPage(String pageNow,String pageSize) throws Exception {
		UserFormMap userFormMap = getFormMap(UserFormMap.class);
		userFormMap=toFormMap(userFormMap, pageNow, pageSize);
//        pageView.setRecords(UserFormMap.mapper().findUserPage(userFormMap));//不调用默认分页,调用自已的mapper中findUserPage
//		 List<User > list = userService.find(a,b);
		 List<User > list = userService.queryByPage(userFormMap);
		pageView.setRecords(list);//不调用默认分页,调用自已的mapper中findUserPage
//		List<Button> btList = buttonService.getButtons("#user");
////		pageView.setButtons(btList);
//		for(Button bt : btList){
//			System.out.println(bt);
//		}
        return pageView;
	}

	@RequestMapping("addUI")
	public String addUI(Model model) throws Exception {
		return Common.BACKGROUND_PATH + "/system/user/add";
	}

	@ResponseBody
	@RequestMapping("addEntity")
	@Transactional(readOnly=false)//需要事务操作必须加入此注解
	public String addEntity(String txtGroupsSelect){
		try {
			System.out.println("addEntity");
			UserFormMap userFormMap = getFormMap(UserFormMap.class);
			String username = (String)userFormMap.get("userName");
			String accountname = (String)userFormMap.get("accountName");
			String password = (String)userFormMap.get("password");
			User user = new User();
			user.setUsername(username);
			user.setAccountname(accountname);
			user.setPassword(password);
			userService.saveUser(user);
		} catch (Exception e) {
			 throw new SystemException("添加账号异常");
		}
		return "success";
	}

	@ResponseBody
	@RequestMapping("deleteEntity")
	@Transactional(readOnly=false)//需要事务操作必须加入此注解
	public String deleteEntity() throws Exception {
		String[] ids = getParaValues("ids");
		for(String a : ids){
			String[] arr = a.split(",");
			userService.deleteUserByIds(arr);
		}
	
		return "success";
	}

	@RequestMapping("editUI")
	public String editUI(Model model) throws Exception {
		String id = getPara("id");
		if(Common.isNotEmpty(id)){
			model.addAttribute("user", new UserFormMap().findById(id));
		}
		return Common.BACKGROUND_PATH + "/system/user/edit";
	}

	@ResponseBody
	@RequestMapping("editEntity")
	@Transactional(readOnly=false)//需要事务操作必须加入此注解
	@SystemLog(module="系统管理",methods="用户管理-修改用户")//凡需要处理业务逻辑的.都需要记录操作日志
	public String editEntity(String txtGroupsSelect) throws Exception {
		UserFormMap userFormMap = getFormMap(UserFormMap.class);
		userFormMap.put("txtGroupsSelect", txtGroupsSelect);
		userFormMap.update();
		new UserGroupsFormMap().deleteByAttribute("userId", userFormMap.get("id"));
		if(!Common.isEmpty(txtGroupsSelect)){
			String[] txt = txtGroupsSelect.split(",");
			UserGroupsFormMap userGroupsFormMap = null;
			for (String roleId : txt) {
			    userGroupsFormMap = new UserGroupsFormMap();
				userGroupsFormMap.put("userId", userFormMap.get("id"));
				userGroupsFormMap.put("roleId", roleId);
				userGroupsFormMap.save();
			}
		}
		return "success";
	}
	/**
	 * 验证账号是否存在
	 * 
	 * @author lanyuan Email：mmm333zzz520@163.com date：2015-2-19
	 * @param name
	 * @return
	 */
	@RequestMapping("isExist")
	@ResponseBody
	public boolean isExist(String name) {
		long n = userService.findUserByName(name);
		if (n < 1) {
			return true;
		} else {
			return false;
		}
	}
	
	//密码修改
	@RequestMapping("updatePassword")
	public String updatePassword(Model model) throws Exception {
		return Common.BACKGROUND_PATH + "/system/user/updatePassword";
	}
	
	//保存新密码
	@RequestMapping("editPassword")
	@ResponseBody
	@Transactional//需要事务操作必须加入此注解
	public Map<String, Object> editPassword(HttpServletRequest request) throws Exception{
		System.out.println("hehe");
		// 当验证都通过后，把用户信息放在session里
		UserFormMap userFormMap = getFormMap(UserFormMap.class);
		User user = (User)request.getSession().getAttribute("user");
		System.out.println(user);
		System.out.println();
		Map<String, Object> map = new HashMap<String, Object>(); 
		String a = user.getPassword();
		String b = (String)userFormMap.get("oldpassword");
		if(!user.getPassword().equals((String)userFormMap.get("oldpassword"))){
			map.put("results", "error");
			map.put("messages", "原密码不正确！！");
		}else{
			user.setPassword((String)userFormMap.get("newpassword"));
			userService.updateUser(user);
			map.put("results", "success");
			map.put("messages", "密码修改成功!");
		}
		return map;
	}
	
	
	@RequestMapping("showarticle")
	public String showarticle(Model model) throws Exception {
		return Common.BACKGROUND_PATH + "/system/user/articlelist";
	}
	
	@RequestMapping("articleeditUI")
	public String articleeditUI(Model model) throws Exception {
		String id = getPara("id");
		if(Common.isNotEmpty(id)){
			model.addAttribute("article", articleService.get(Integer.parseInt(id)));
		}
		return Common.BACKGROUND_PATH + "/system/user/articleedit";
	}
}